package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javacompress.CompressingFileSVGZ;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import svgedit.gui.Frame;
import svgedit.gui.SVGZFileFilter;

/**
 * Shows discard changes dialog, then sets the document to a new, empty
 * document.
 */
@SuppressWarnings("serial")
public class SveAsSVGZAction extends AbstractAction
{
    
    private Frame frame;
    private CompressingFileSVGZ compressingFileSVGZ;
    
    /** Create this action for the given frame */
    public SveAsSVGZAction(Frame frame)
    {
        super("Exort as SVGZ");
        this.frame = frame;
    }
    
    public void actionPerformed(ActionEvent ae)
    {
        File file = frame.getDocument().getFile();
        JFileChooser dialog;
        if (file != null)
            dialog = new JFileChooser(file);
        else
            dialog = new JFileChooser(frame.getPreferences().getDefaultPath());
        dialog.addChoosableFileFilter(new SVGZFileFilter());
        
        dialog.showSaveDialog(null);
        
        file = dialog.getSelectedFile();
        if (file != null)
        {
            if (file.getPath().toLowerCase().endsWith(".svgz") == false)
                file = new File(file.getPath() + ".svgz");
            
            if (file.exists())
            {
                if (JOptionPane.showConfirmDialog(frame.getRootPane(),
                        String.format(
                                "Do you want to replace the existing file " +
                                        "named %s?", file.getName()),
                        "Overwrite existing file?",
                        JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
                    return;
            }
            
            frame.getPreferences().setDefaultPath(file.getPath());
            frame.saveFile(file);
            this.compressingFileSVGZ = new CompressingFileSVGZ(file.getPath()
                    .toLowerCase().toString());
            compressingFileSVGZ.doCompressFile(file.getPath().toLowerCase()
                    .toString());
            
            // file.close();
            System.out.println(file.getPath().toString());
            File ff = new File(file.getPath() + ".svgz" + ".svgz");
            frame.getDocument().setFile(ff);
            boolean success = file.delete();
            if (!success)
            {
                System.out.println("Deletion failed.");
            }
            else
            {
                System.out.println("File deleted.");
            }
            
        }
        
    }
    
    public void setText(String Text)
    {
        setText(Text);
    }
    
}
